# encoding=utf-8
import base64
import os
import shutil
import time
import traceback

from flask import Response
from seg_common.FileService import DirPackage
from seg_system.Download.service.DownloadDirFactory import DownloadDirFactory


class DownloadService:
    @staticmethod
    def download_zip_file(saver: DownloadDirFactory, user_name: str, token: str, **kwargs):
        zip_file = os.path.join(saver.NORMAL_0, '{}_{}.zip'.format(user_name, token))
        file_name = DirPackage.pack_zip(saver.NORMAL_1, zip_file)

        def send():
            with open(zip_file, 'rb') as file:
                while True:
                    data = file.read(20 * 1024 * 1024)  # 20M
                    if not data:
                        break
                    yield data

        response = Response(send(), content_type='application/octet-stream')
        response.headers["Access-Control-Expose-Headers"] = "Content-Disposition"
        response.headers["Content-Disposition"] = 'attachment; filename={}'.format(file_name.encode('utf-8').decode('ISO-8859-1'))
        return response

    @staticmethod
    def download_zip_file_with_label(saver: DownloadDirFactory, user_name: str, token: str, **kwargs):
        # 2022.9.15需求修改，需要调整为中文目录
        # 由于并发系统设计问题，如果直接修改映射目录为中文，容易出现难以解决的bug
        # 此函数的作用就是把结果拷贝到一个临时文件夹中进行修改，这样子出了难以解决的中文bug也好修复

        # 2022.9.16增加中英下载
        LAG_DICT = kwargs.get('LAG_DICT')
        assert LAG_DICT is not None

        # 创建一个服务器时间的目录
        local_dir = time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime(time.time()))
        abs_local_dir = os.path.join(saver.NORMAL_0, local_dir)
        # ApplicationConfig.PathConfig.make_dir(abs_local_dir)

        # 文件复制并改名
        # 容易出现文件符号异常问题，且难以查找
        try:
            shutil.copytree(saver.NORMAL_1, abs_local_dir)
            # 逐个进入并改名
            dir_seq = []  # 遍历完成再改变
            name_change_seq = []

            # 没有do while来着
            # 这部分如果文件夹改动，需要自己修
            # 判断是否存在是有些文件夹不需要改名/或者还没使用
            for each_dir in os.listdir(abs_local_dir):
                o_n = os.path.join(abs_local_dir, each_dir)
                if each_dir in LAG_DICT:
                    c_n = os.path.join(abs_local_dir, LAG_DICT[each_dir])
                    name_change_seq.append((o_n, c_n))
                dir_seq.append(o_n)

            while len(dir_seq) > 0:
                d = dir_seq.pop(0)
                for each_dir in os.listdir(d):
                    if os.path.isdir(os.path.join(d, each_dir)):
                        o_n = os.path.join(d, each_dir)
                        if each_dir in LAG_DICT:
                            c_n = os.path.join(d, LAG_DICT[each_dir])
                            name_change_seq.append((o_n, c_n))
                        dir_seq.append(o_n)

            # 迭代完成后改名(逆序，否则顶层文件夹修改导致后续变化)
            for each_o, each_to in name_change_seq[::-1]:
                os.rename(each_o, each_to)

            zip_file = os.path.join(saver.NORMAL_0, '{}_{}.zip'.format(user_name, token))
            file_name = DirPackage.pack_zip(abs_local_dir, zip_file)

            # 懒得写定时清理了，直接删除原文件夹
            shutil.rmtree(abs_local_dir)

            def send():
                with open(zip_file, 'rb') as file:
                    while True:
                        data = file.read(20 * 1024 * 1024)  # 20M
                        if not data:
                            break
                        yield data

            response = Response(send(), content_type='application/octet-stream')
            response.headers["Access-Control-Expose-Headers"] = "Content-Disposition"
            response.headers["Content-Disposition"] = 'attachment; filename={}'.format(
                file_name.encode('utf-8').decode('ISO-8859-1'))

            return response

        except Exception as e:
            print(traceback.format_exc())
            return str(e)







